# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.models import User, Group, Permission
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from accounts.models import StudentSurvey
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
import re


def is_superuser(user):
    return user.is_superuser


@login_required
@user_passes_test(is_superuser, login_url='/login/')
def user_manage_view(request):
    """用户管理视图"""
    search_query = request.GET.get('q', '')

    if search_query:
        users = User.objects.filter(
            Q(username__icontains=search_query) |
            Q(email__icontains=search_query) |
            Q(first_name__icontains=search_query) |
            Q(last_name__icontains=search_query)
        ).order_by('-date_joined')
    else:
        users = User.objects.all().order_by('-date_joined')

    # 分页
    paginator = Paginator(users, 10)  # 每页显示10个用户
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'page_obj': page_obj,
        'search_query': search_query,
        'total_users': users.count(),
    }

    return render(request, 'supper/user_manage.html', context)


@login_required
@user_passes_test(is_superuser, login_url='/login/')
def role_manage_view(request):
    """角色管理视图"""
    search_query = request.GET.get('q', '')

    if search_query:
        groups = Group.objects.filter(name__icontains=search_query).order_by('name')
    else:
        groups = Group.objects.all().order_by('name')

    # 分页
    paginator = Paginator(groups, 10)  # 每页显示10个角色
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    # 获取所有权限
    permissions = Permission.objects.all().order_by('content_type__app_label', 'codename')

    context = {
        'page_obj': page_obj,
        'search_query': search_query,
        'total_groups': groups.count(),
        'permissions': permissions,
    }

    return render(request, 'supper/role_manage.html', context)


@login_required
@user_passes_test(is_superuser, login_url='/login/')
def add_user_view(request):
    """添加用户视图"""
    if request.method == 'POST':
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        is_staff = request.POST.get('is_staff') == 'on'
        is_superuser = request.POST.get('is_superuser') == 'on'
        groups = request.POST.getlist('groups')

        # 创建用户
        try:
            # 验证密码
            try:
                validate_password(password)
            except ValidationError as e:
                # 将错误信息翻译为中文
                error_messages = []
                for error in e.messages:
                    if 'too short' in error:
                        error_messages.append("密码长度不足，至少需要6个字符")
                    elif 'too similar' in error:
                        error_messages.append("密码与用户名太相似")
                    elif 'too common' in error:
                        error_messages.append("这个密码太常见了")
                    elif 'entirely numeric' in error and not re.match(r'^\d{6}$', password):
                        error_messages.append("密码不能全是数字，除非是6位数字密码")
                    else:
                        error_messages.append(error)

                messages.error(request, f'密码验证失败: {"; ".join(error_messages)}')
                context = {
                    'groups': Group.objects.all()
                }
                return render(request, 'supper/add_user.html', context)

            user = User.objects.create_user(
                username=username,
                email=email,
                password=password
            )
            user.is_staff = is_staff
            user.is_superuser = is_superuser
            user.save()

            # 添加用户到选定的组
            for group_id in groups:
                group = Group.objects.get(id=group_id)
                user.groups.add(group)

            messages.success(request, f'用户 {username} 创建成功！')
            return redirect('user_manage')
        except Exception as e:
            messages.error(request, f'创建用户失败: {str(e)}')

    context = {
        'groups': Group.objects.all()
    }
    return render(request, 'supper/add_user.html', context)


@login_required
@user_passes_test(is_superuser, login_url='/login/')
def edit_user_view(request, user_id):
    """编辑用户视图"""
    user = get_object_or_404(User, id=user_id)

    if request.method == 'POST':
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        is_staff = request.POST.get('is_staff') == 'on'
        is_superuser = request.POST.get('is_superuser') == 'on'
        groups = request.POST.getlist('groups')

        try:
            # 如果提供了新密码，验证它
            if password:
                try:
                    validate_password(password)
                except ValidationError as e:
                    # 将错误信息翻译为中文
                    error_messages = []
                    for error in e.messages:
                        if 'too short' in error:
                            error_messages.append("密码长度不足，至少需要6个字符")
                        elif 'too similar' in error:
                            error_messages.append("密码与用户名太相似")
                        elif 'too common' in error:
                            error_messages.append("这个密码太常见了")
                        elif 'entirely numeric' in error and not re.match(r'^\d{6}$', password):
                            error_messages.append("密码不能全是数字，除非是6位数字密码")
                        else:
                            error_messages.append(error)

                    messages.error(request, f'密码验证失败: {"; ".join(error_messages)}')
                    context = {
                        'user_obj': user,
                        'groups': Group.objects.all(),
                        'user_groups': [g.id for g in user.groups.all()],
                    }
                    return render(request, 'supper/edit_user.html', context)

            user.username = username
            user.email = email
            if password:
                user.set_password(password)
            user.is_staff = is_staff
            user.is_superuser = is_superuser
            user.save()

            # 更新用户组
            user.groups.clear()
            for group_id in groups:
                group = Group.objects.get(id=group_id)
                user.groups.add(group)

            messages.success(request, f'用户 {username} 更新成功！')
            return redirect('user_manage')
        except Exception as e:
            messages.error(request, f'更新用户失败: {str(e)}')

    context = {
        'user_obj': user,
        'groups': Group.objects.all(),
        'user_groups': [g.id for g in user.groups.all()],
    }
    return render(request, 'supper/edit_user.html', context)


@login_required
@user_passes_test(is_superuser, login_url='/login/')
def delete_user_view(request, user_id):
    """删除用户视图"""
    user = get_object_or_404(User, id=user_id)

    try:
        username = user.username
        user.delete()
        messages.success(request, f'用户 {username} 已删除')
    except Exception as e:
        messages.error(request, f'删除用户失败: {str(e)}')

    return redirect('user_manage')


@login_required
@user_passes_test(is_superuser, login_url='/login/')
def add_role_view(request):
    """添加角色视图"""
    if request.method == 'POST':
        name = request.POST.get('name')
        permissions = request.POST.getlist('permissions')

        try:
            group = Group.objects.create(name=name)

            # 添加权限
            for perm_id in permissions:
                perm = Permission.objects.get(id=perm_id)
                group.permissions.add(perm)

            messages.success(request, f'角色 {name} 创建成功！')
            return redirect('role_manage')
        except Exception as e:
            messages.error(request, f'创建角色失败: {str(e)}')

    context = {
        'permissions': Permission.objects.all().order_by('content_type__app_label', 'codename')
    }
    return render(request, 'supper/add_role.html', context)


@login_required
@user_passes_test(is_superuser, login_url='/login/')
def edit_role_view(request, role_id):
    """编辑角色视图"""
    group = get_object_or_404(Group, id=role_id)

    if request.method == 'POST':
        name = request.POST.get('name')
        permissions = request.POST.getlist('permissions')

        try:
            group.name = name
            group.save()

            # 更新权限
            group.permissions.clear()
            for perm_id in permissions:
                perm = Permission.objects.get(id=perm_id)
                group.permissions.add(perm)

            messages.success(request, f'角色 {name} 更新成功！')
            return redirect('role_manage')
        except Exception as e:
            messages.error(request, f'更新角色失败: {str(e)}')

    context = {
        'group': group,
        'permissions': Permission.objects.all().order_by('content_type__app_label', 'codename'),
        'group_permissions': [p.id for p in group.permissions.all()],
    }
    return render(request, 'supper/edit_role.html', context)


@login_required
@user_passes_test(is_superuser, login_url='/login/')
def delete_role_view(request, role_id):
    """删除角色视图"""
    group = get_object_or_404(Group, id=role_id)

    try:
        name = group.name
        group.delete()
        messages.success(request, f'角色 {name} 已删除')
    except Exception as e:
        messages.error(request, f'删除角色失败: {str(e)}')

    return redirect('role_manage')


@login_required
@user_passes_test(is_superuser, login_url='/login/')
def data_upload_view(request):
    # 获取上传的文件统计
    import os
    from django.conf import settings

    media_path = os.path.join(settings.BASE_DIR, 'media')
    files = []

    if os.path.exists(media_path):
        for file in os.listdir(media_path):
            if file.endswith('.xlsx'):
                file_path = os.path.join(media_path, file)
                file_stat = os.stat(file_path)
                files.append({
                    'name': file,
                    'size': file_stat.st_size,
                    'created': file_stat.st_ctime,
                    'modified': file_stat.st_mtime,
                })

    context = {
        'files': sorted(files, key=lambda x: x['modified'], reverse=True),
        'user': request.user,
    }
    return render(request, 'supper/data_upload.html', context)


@login_required
@user_passes_test(is_superuser, login_url='/login/')
def data_manage_view(request):
    """数据管理视图 - 展示已有数据"""
    search_query = request.GET.get('q', '')

    if search_query:
        data = StudentSurvey.objects.filter(
            Q(id__icontains=search_query) |
            Q(gender__icontains=search_query) |
            Q(age__icontains=search_query)
        ).order_by('-created_at')
    else:
        data = StudentSurvey.objects.all().order_by('-created_at')

    # 分页 - 减少每页显示的数据量，因为字段较多
    page_size = request.GET.get('page_size', 10)
    paginator = Paginator(data, page_size)  # 每页显示10条数据
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    # 对年龄字段进行处理保留 2 位小时
    for item in page_obj:
        item.age = round(item.age, 2)

    context = {
        'page_obj': page_obj,
        'search_query': search_query,
        'total_records': data.count(),
    }

    return render(request, 'supper/data_manage.html', context)
